<template>
  <div class="article-list" ref="list" @scroll="rememberScrollTop">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <article-item
        v-for="article in articleList"
        :key="article.art_id"
        :article="article"
      />
    </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import articleItem from './articleItem.vue'
import { getChannelArticleList } from '@/api/channel'
export default {
  props: ['currentId'],
  data () {
    return {
      timestamp: +new Date(),
      articleList: [],
      loading: false,
      finished: false,
      refreshing: false,
      scrollTop: 0
    }
  },
  components: {
    articleItem
  },
  created () {
    //   请求当前频道下的文章列表数据
    this.getArticleListByChannelId()
  },
  // keep-alive  ... 重新进入缓存组件中去
  activated () {
    this.$refs.list.scrollTop = this.scrollTop
  },
  methods: {
    rememberScrollTop () {
      // console.log(this.$refs.list.scrollTop)
      this.scrollTop = this.$refs.list.scrollTop
    },
    async onRefresh () {
      this.refreshing = true

      this.timestamp = +new Date()
      const [err, data] = await getChannelArticleList({
        channel_id: this.currentId,
        timestamp: this.timestamp
      })
      if (err) return this.$toast.fail(err)

      this.articleList = data.data.results

      // 去除刷新的状态
      this.refreshing = false
    },
    onLoad () {
      // console.log('加载更多')
      this.getArticleListByChannelId()
    },
    async getArticleListByChannelId () {
      // 正在加载中
      this.loading = true
      const [err, data] = await getChannelArticleList({
        channel_id: this.currentId,
        timestamp: this.timestamp
      })
      if (err) return this.$toast.fail(err)
      // 没有数据了
      if (data.data && data.data.results && data.data.results.length === 0) {
        this.loading = false
        this.finished = true
        return
      }

      //   console.log(data)
      this.articleList.push(...data.data.results)
      // 覆盖当前的时间戳
      this.timestamp = data.data.pre_timestamp
      // 请求完毕
      this.loading = false
    }
  }
}
</script>
<style scoped lang="less">
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
